package com.example.summary.thread;

/**
 * Created by wzn on 2019/6/20.
 */
public class TestSynchronized {

    private int number = 0;

    public synchronized void increment() throws InterruptedException {
        System.out.println("------------" + Thread.currentThread().getName() + "\t" + number);
        if (number != 0) {
            this.wait();
        }

        number++;
        System.out.println("++++++++++++" + Thread.currentThread().getName() + "\t" + number);
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        System.out.println("------------" + Thread.currentThread().getName() + "\t" + number);
        if (number == 0) {
            this.wait();
        }

        number--;
        System.out.println("++++++++++++" + Thread.currentThread().getName() + "\t" + number);

        this.notify();
    }

    public static void main(String[] args) throws InterruptedException {

        TestSynchronized testSynchronized = new TestSynchronized();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    testSynchronized.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "AA1").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    testSynchronized.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "AA2").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    testSynchronized.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "BB").start();


        Thread.sleep(5000L);
        System.out.println(testSynchronized.number);
    }
}
